package com.example.elemboot.Utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.example.elemboot.Dao.IUser;
import com.example.elemboot.Entity.User;
import com.example.elemboot.exception.ServiceException;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;



@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private IUser userDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("\n-------- LogInterception.preHandle --- ");
        System.out.println("Request URL: " + request.getRequestURL());

        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            token = request.getParameter("token");
        }
        System.out.println("token = " + token);
        //通过注解放行
//        if (handler instanceof HandlerMethod){
//            AuthAccess access = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
//            if (access != null){
//                return true;
//            }
//        }
        //执行认证
        if(StringUtils.isEmpty(token)){
            throw new ServiceException("401","请登录");
        }

        //获取token里面的userid
        String userPhone;
        try {
            userPhone = JWT.decode(token).getAudience().get(0);
            System.out.println("userPhone = " + userPhone);
        }catch (JWTDecodeException j){
            throw new ServiceException("401","请登录");
        }

        //根据token的userPhone查询数据库
        User user = userDao.findUserByUserPhone(userPhone);
        if (user == null){
            throw new ServiceException("401","请登录");
        }

        //通过密码生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
        try {
            jwtVerifier.verify(token); //验证token
        }catch (JWTDecodeException j){
            throw new ServiceException("401","请登录");
        }
        return true;
    }
}
